﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace MyPublisher.Configuration
{
    public class CompositionConfiguration : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }

        [ConfigurationProperty("type")]
        public string Type
        {
            get { return (string)this["type"]; }
            set { this["type"] = value; }
        }

        public Type CompositionType { get { return System.Type.GetType(Type); } }

        public CompositionConfiguration() { }
    }

    public class CompositionsConfiguration : ConfigurationElementCollection
    {
        public CompositionsConfiguration()
        {
        }

        protected override ConfigurationElement CreateNewElement()
        {
            return new CompositionConfiguration();
        }

        protected override Object GetElementKey(ConfigurationElement element)
        {
            return ((CompositionConfiguration)element).Name;
        }

        [ConfigurationProperty("defaultProvider")]
        public string DefaultProvider
        {
            get { return (string)base["defaultProvider"]; }
            set { base["defaultProvider"] = value; }
        }

        public CompositionConfiguration DefaultConfiguration { get { return this[DefaultProvider]; } }

        public Type DefaultProviderType { get { return DefaultConfiguration.CompositionType; } }

        public CompositionConfiguration this[int index]
        {
            get { return (CompositionConfiguration)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                BaseAdd(index, value);
            }
        }

        public CompositionConfiguration this[string name]
        {
            get { return (CompositionConfiguration)BaseGet(name); }
            set
            {
                ConfigurationElement element = BaseGet(name);
                int index = -1;
                if (element != null)
                {
                    index = BaseIndexOf(element);
                    BaseRemove(name);
                }
                if (index != -1)
                {
                    BaseAdd(index, value);
                }
                else
                {
                    BaseAdd(value);
                }
            }
        }
    }
}
